package com.blame.onlinemusicserver.service;


import com.blame.onlinemusicserver.mapper.UserMapper;
import com.blame.onlinemusicserver.model.User;
import com.blame.onlinemusicserver.tools.Constant;
import com.blame.onlinemusicserver.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public ResponseBodyMessage<User> login(String username,
                      String password,
                      HttpServletRequest request) {
        User loginUser=new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);
        User user=userMapper.selectByName(username);
        if(user==null){
            return new ResponseBodyMessage<>(-1,"用户不存在",loginUser);
        }
        if(!bCryptPasswordEncoder.matches(password,user.getPassword())){
            return new ResponseBodyMessage<>(-1,"密码错误，请重新登录",loginUser);
        }else {
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(0,"登陆成功",loginUser);
        }

    }

    public ResponseBodyMessage<Boolean> register(String username,String password,String email){
        User existUser=userMapper.selectByName(username);
        if(existUser!=null){
            return new ResponseBodyMessage<>(-1,"该用户存在",false);
        }
//        将注册的密码进行加密
        String encoderPassword=bCryptPasswordEncoder.encode(password);
        User user=new User();
        user.setUsername(username);
        user.setPassword(encoderPassword);
        user.setEmail(email);
        userMapper.insertUser(user);
        return new ResponseBodyMessage<>(0,"注册成功",true);
    }
}
